package com.tomcat.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.whu.sang.kps.search.QueryManager;
import edu.whu.sang.kps.search.graphStruct.SimpleAnswer;
import edu.whu.sang.util.Tool;

public class FindResult extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	QueryManager qm = null;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		String keywords = req.getParameter("keyword");
		
		if(keywords!=null){
			keywords = keywords.trim().toLowerCase();
			//对关键词过滤
			Pattern p = Pattern.compile(" {2,}");
			Matcher m = p.matcher(keywords);
			keywords = m.replaceAll(" ");
			//记录时间
			Date start = new Date();
			SimpleAnswer[] simpleAnswer = qm.search(keywords, 60);
			Date end = new Date();
			req.setAttribute("time",(end.getTime()-start.getTime())*1.0/1000+"s" );
			
	        req.setAttribute("result", simpleAnswer);
	        req.setAttribute("returnKey", keywords);
	        req.getRequestDispatcher("finder.jsp").forward(req,resp);
		}else{
			//log
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
		Tool.setPath(this.getServletContext().getRealPath("")+"/");//必须加上 "/"
		qm = QueryManager.getInstance();
	} 	

}
